package com.szbmyoubao.app.ui.version

import com.szbmyoubao.app.bean.request.VersionInfoRequest
import com.szbmyoubao.app.bean.response.AppVersionResponse
import com.szbmyoubao.app.http.request
import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.ktx.postEvent
import com.ellecity06.common.utils.CommonUtils
import com.ellecity06.common.utils.appContext

/**
 * @author ellecity06
 * @time 2024/11/1 11:04
 * @des
 */
class VersionUpdateViewModel : BaseMviViewModel<VersionUpdateState, VersionUpdateIntent>() {
    private var versionResponse: AppVersionResponse? = null
    private val versionCode: Int by lazy { CommonUtils.getVersionCode(appContext) }
    override suspend fun collectIntent(it: VersionUpdateIntent) {
        when (it) {
            VersionUpdateIntent.FetchLastVersion -> {
                lastVersion()
            }
            VersionUpdateIntent.ShowUpdateDialog -> {
                if (versionResponse != null && versionCode > 0 && versionCode < versionResponse!!.versionNum) {
                    mState.postEvent(VersionUpdateState.ShowDialog(versionResponse!!))
                }
            }
        }
    }

    private fun lastVersion() {
        request(api = { lastVersion(VersionInfoRequest()) }, success = {
            if (it != null) {
                versionResponse = it
                mState.postEvent(VersionUpdateState.Success(versionCode > 0 && versionCode < it.versionNum))
            } else {
                mState.postEvent(VersionUpdateState.Error)
            }

        },  error = {
                showToast(it.message)
                mState.postEvent(VersionUpdateState.Error)

        })
    }
}